package com.dokimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.dokimall.common.utils.R;
import com.dokimall.product.entity.SkuImagesEntity;
import com.dokimall.product.entity.SpuInfoDescEntity;
import com.dokimall.product.feign.SeckillFeignService;
import com.dokimall.product.service.*;
import com.dokimall.product.vo.SeckillRedisVo;
import com.dokimall.product.vo.SkuItemSaleAttrVo;
import com.dokimall.product.vo.SkuItemVo;
import com.dokimall.product.vo.SpuItemAttrGroupVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dokimall.common.utils.PageUtils;
import com.dokimall.common.utils.Query;

import com.dokimall.product.dao.SkuInfoDao;
import com.dokimall.product.entity.SkuInfoEntity;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    SkuImagesService skuImagesService;
    @Autowired
    SpuInfoDescService spuInfoDescService;
    @Autowired
    AttrGroupService attrGroupService;
    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    ThreadPoolExecutor poolExecutor;
    @Autowired
    SeckillFeignService seckillFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils listSkuInfo(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> queryWrapper = new QueryWrapper<>();

        /**
         * key: '华为',//检索关键字
         * catelogId: 0,
         * brandId: 0,
         * min: 0,
         * max: 0
         * */

        String key = (String)params.get("key");
        if(StringUtils.isNotEmpty(key)){
            queryWrapper.and((w)->{
                w.eq("sku_id",key).or().like("sku_name",key);
            });
        }

        String catelogId = (String)params.get("catelogId");
        if(StringUtils.isNotEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)){
            queryWrapper.eq("catalog_id",catelogId);
        }

        String brandId = (String)params.get("brandId");
        if(StringUtils.isNotEmpty(brandId) && !"0".equalsIgnoreCase(brandId)){
            queryWrapper.eq("brand_id",brandId);
        }

        String min = (String)params.get("min");
        if(StringUtils.isNotEmpty(min) && !"0".equalsIgnoreCase(min)){
            queryWrapper.ge("price",min);
        }

        String max = (String)params.get("max");
        if(StringUtils.isNotEmpty(max) && !"0".equalsIgnoreCase(max)){
            queryWrapper.le("price",max);
        }

        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);

    }

    @Override
    public List<SkuInfoEntity> listBySpuId(Long spuId) {
        List<SkuInfoEntity> skuInfoEntities = this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        return skuInfoEntities;
    }

    @Override
    public SkuItemVo item(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVo skuItemVo = new SkuItemVo();
        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
            //1、sku基本信息获取 pms_sku_info
            SkuInfoEntity skuInfo = this.getOne(new QueryWrapper<SkuInfoEntity>().eq("sku_id", skuId));
            skuItemVo.setSkuInfo(skuInfo);
            return skuInfo;
        }, poolExecutor);

        CompletableFuture<Void> skuSaleItemFuture = infoFuture.thenAcceptAsync((res) -> {
            //3、获取sku的销售属性组合
            List<SkuItemSaleAttrVo> saleAttrVos = skuSaleAttrValueService.getSkuAttrBySpuId(res.getSpuId());
            skuItemVo.setSaleAttr(saleAttrVos);
        },poolExecutor);

        CompletableFuture<Void> spuInfoFuture = infoFuture.thenAcceptAsync((res) -> {
            //4、获取spu的介绍
            SpuInfoDescEntity spuInfoDesc = spuInfoDescService.getOne(new QueryWrapper<SpuInfoDescEntity>().eq("spu_id", res.getSpuId()));
            skuItemVo.setDesp(spuInfoDesc);
        }, poolExecutor);

        CompletableFuture<Void> spuAttrFuture = infoFuture.thenAcceptAsync((res) -> {
            //5、获取spu的规格参数信息
            List<SpuItemAttrGroupVo> spuAttrInfos = attrGroupService.getSpuAttrInfo(res.getSpuId(), res.getCatalogId());
            skuItemVo.setGroupAttrs(spuAttrInfos);
        }, poolExecutor);

        //2、sku的图片信息 pms_sku_images
        CompletableFuture<Void> imageFuture = CompletableFuture.runAsync(() -> {
            List<SkuImagesEntity> skuImages = skuImagesService.getSkuImages(skuId);
            skuItemVo.setImages(skuImages);
        }, poolExecutor);

        // 查寻该商品是否为秒杀商品
        CompletableFuture<Void> seckillFuture = CompletableFuture.runAsync(() -> {
            R r = seckillFeignService.getSkuSeckillInfo(skuId);
            if (r.getCode() == 0) {

                SeckillRedisVo seckillRedisVo = r.getData(new TypeReference<SeckillRedisVo>() {
                });
                if(seckillRedisVo!=null){
                    long now = new Date().getTime();
                    if (now < seckillRedisVo.getStartTime()) {
                        // 还未到秒杀时间，把随机码隐藏掉
                        seckillRedisVo.setToken(null);
                    }
                    skuItemVo.setSeckillRedisVo(seckillRedisVo);
                }
            }
        }, poolExecutor);


        // 当所有线程任务完成后,才进行返回
        CompletableFuture.allOf(skuSaleItemFuture,spuInfoFuture,spuAttrFuture,imageFuture,seckillFuture).get();

        return skuItemVo;
    }

    @Override
    public BigDecimal getNewPrice(Long skuId) {
        SkuInfoEntity skuInfoEntity = this.getOne(new QueryWrapper<SkuInfoEntity>().eq("sku_id", skuId));
        return skuInfoEntity.getPrice();
    }

}